<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="header">
			<view class="header-left" :style="{ marginTop: safeTop + 'px' }" @click="goToBack">
				<image src="/static/base/back.svg" class="menu-icon" mode="aspectFit" />
			</view>
			<view class="header-title" :style="{ marginTop: safeTop + 'px' }">居间人申请</view>
			<view class="header-right"></view>
		</view>

		<!-- 表单内容 -->
		<view class="form-container" :style="{ paddingTop: headerHeight + 'px' }">

			<!-- 居间人姓名 -->
			<view class="form-item">
				<text class="label">居间人姓名：</text>
				<text v-if="isFormDisabled && !formData.name" class="placeholder">--</text>
				<input :disabled="isFormDisabled" type="text" :placeholder="isFormDisabled ? '' : '请输入姓名'" class="input"
					:style="{ color: isFormDisabled ? '#999' : '#333' }" v-model="formData.name" />
			</view>

			<!-- 性别 -->
			<view class="form-item">
				<text class="label">性别：</text>
				<text v-if="isFormDisabled && !formData.gender" class="placeholder">--</text>
				<input :disabled="isFormDisabled" type="text" :placeholder="isFormDisabled ? '' : '请输入性别（男/女）'"
					class="input" :style="{ color: isFormDisabled ? '#999' : '#333' }" v-model="formData.gender" />
			</view>

			<!-- 从业时长 -->
			<view class="form-item">
				<text class="label">从业时长：</text>
				<text v-if="isFormDisabled && !formData.years" class="placeholder">--</text>
				<input :disabled="isFormDisabled" type="text" :placeholder="isFormDisabled ? '' : '例如：3年'" class="input"
					:style="{ color: isFormDisabled ? '#999' : '#333' }" v-model="formData.years" />
			</view>

			<!-- 联系电话 -->
			<view class="form-item">
				<text class="label">联系电话：</text>
				<input v-if="formData.phone" disabled type="tel" placeholder="绑定手机号" class="input"
					:style="{ color: '#333' }" v-model="formData.phone" />
				<text v-else-if="!isFormDisabled" @click="toBindPhone" class="input"
					:style="{ color: '#333' }">绑定手机号</text>
				<text v-else class="input" :style="{ color: '#999' }">{{ formData.phone || '未绑定' }}</text>
			</view>

			<!-- 上传身份证 -->
			<view class="upload-section">
				<text class="section-title">上传身份证</text>
				<view class="id-card-container">
					<view class="card-item" @click="!isFormDisabled && chooseImage('front')">
						<image
							:src="formData.idFront || 'https://test.accmee.com//uploads/attach/2025/10/20251006/24243f871d2986ffd1575c363ec00896.png'"
							class="card-image" mode="aspectFill" />
					</view>
					<view class="card-item" @click="!isFormDisabled && chooseImage('back')">
						<image
							:src="formData.idBack || 'https://test.accmee.com//uploads/attach/2025/10/20251006/4d5695a3f3e09a79cae981fae2560984.png'"
							class="card-image" mode="aspectFill" />
					</view>
				</view>
			</view>

			<!-- 示例图说明 -->
			<view class="example-section">
				<text class="example-title">持有的本人有效二代身份证：</text>
				<text class="example-tip">拍摄时确保身份证<text style="color: #FF0000;">边框完整、字体清晰、亮度均匀；</text></text>
				<view class="example-images">
					<view class="example-item">
						<image
							src="https://test.accmee.com//uploads/attach/2025/10/20251006/b41a7e7765e6b80a42c2b364e12c7476.png"
							class="example-img" mode="aspectFill" />
						<text class="example-label">标准</text>
					</view>
					<view class="example-item">
						<image
							src="https://test.accmee.com//uploads/attach/2025/10/20251006/dc0941a7422b502c73d6f8d406f1f854.png"
							class="example-img" mode="aspectFill" />
						<text class="example-label">边框缺失</text>
					</view>
					<view class="example-item">
						<image
							src="https://test.accmee.com//uploads/attach/2025/10/20251006/d9aecd870fb65cd76eb5cca59631a2e0.png"
							class="example-img" mode="aspectFill" />
						<text class="example-label">照片模糊</text>
					</view>
					<view class="example-item">
						<image
							src="https://test.accmee.com//uploads/attach/2025/10/20251006/71c48509b98d9914677f126baad6c7f5.png"
							class="example-img" mode="aspectFill" />
						<text class="example-label">闪光强烈</text>
					</view>
				</view>
			</view>

			<!-- 上传资质 -->
			<view class="upload-resume-section">
				<text class="section-title">上传资质</text>
				<view class="resume-upload" @click="chooseResume">
					<image v-if="formData.resume" :src="formData.resume" class="resume-preview" mode="aspectFill" />
					<view v-else class="resume-add">
						<text class="add-icon">+</text>
					</view>
				</view>
			</view>

			<!-- 提交按钮 -->
			<view class="submit-btn" :class="{ 'disabled': isFormDisabled }" @click="submitForm">
				{{ submitBtnText }}
			</view>
		</view>
	</view>
</template>

<script>
	import {
		betweenAuditSubmit,
		getUserIdentityStatus
	} from '@/api/base/user-center.js'
	import {
		mapGetters
	} from 'vuex'
	import {
		getBaseUserInfo
	} from '@/api/base/user-center'
	import Cache from '@/utils/cache'

	export default {
		data() {
			return {
				safeTop: 0,
				headerHeight: 0,
				userInfo: {},
				auditIdentity: 0, // 审核身份类型 (0: 未提交, 3: 居间人审核中)
				intermediaryAuditStatus: null, // 居间人审核状态 (0: 审核中, 2: 拒绝)
				hasShownRejectModal: false,
				formData: {
					invite_uid: '',
					invite_Name: '邀请人',
					name: '',
					gender: '',
					years: '',
					phone: '',
					idFront: '',
					idBack: '',
					resume: ''
				}
			}
		},

		computed: {
			...mapGetters(['isLogin']),

			// 表单是否禁用
			isFormDisabled() {
				// 只有在审核中 (auditIdentity=3 且 intermediaryAuditStatus=0) 时才禁用
				return this.auditIdentity === 3 && this.intermediaryAuditStatus === 0;
			},

			// 提交按钮文本
			submitBtnText() {
				if (this.auditIdentity === 3 && this.intermediaryAuditStatus === 0) {
					return '居间人信息审核中';
				} else if (this.auditIdentity === 3 && this.intermediaryAuditStatus === 2) {
					return '重新提交审核';
				} else {
					// auditIdentity === 0 或其他情况
					return '提交审核';
				}
			}
		},

		onLoad(option) {
			const {
				barTop
			} = this.$util.getWXStatusHeight()
			this.safeTop = barTop
			this.headerHeight = 45 + barTop

			if (option.invite_uid) {
				this.formData.invite_uid = option.invite_uid
				this.formData.invite_Name = option.invite_Name
				this.formData.phone = option.phoneNumber
			}
			
		},

		onShow() {
			
			if (this.isLogin) {
				this.checkIdentityStatus()
			} else {
				let back_url =
					`/pages/sub_base/between-apply/index?invite_uid=${this.formData.invite_uid}&invite_Name=${this.formData.invite_Name}`
				Cache.set('login_back_url', back_url)
				//#ifdef MP
				uni.navigateTo({
					url: '/pages/users/wechat_login/index'
				})
				//#endif
				//#ifdef H5
				uni.navigateTo({
					url: '/pages/users/login/index'
				})
				//#endif
			}
		},

		methods: {
			goToBack() {
				uni.navigateBack();
			},

			toBindPhone() {
				uni.navigateTo({
					url: '/pages/users/user_phone/index?type=1&backType=10'
				})
			},

			chooseImage(type) {
				if (this.isFormDisabled) return
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						const tempFilePath = res.tempFilePaths[0]
						if (type === 'front') {
							this.formData.idFront = tempFilePath
						} else if (type === 'back') {
							this.formData.idBack = tempFilePath
						}
					}
				})
			},

			chooseResume() {
				if (this.isFormDisabled) return
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						this.formData.resume = res.tempFilePaths[0]
					}
				})
			},

			parseSex(genderStr) {
				if (genderStr === '1' || genderStr === 1) return 1
				if (genderStr === '2' || genderStr === 2) return 2
				if (genderStr === '男') return 1
				if (genderStr === '女') return 2
				return null
			},

			uploadImage(tempPath) {
				return new Promise((resolve, reject) => {
					this.$util.uploadImgs(
						'upload/image',
						tempPath,
						(res) => {
							if (res.status === 200) {
								const url = res.data?.url || res.url || ''
								if (url) {
									resolve(url)
								} else {
									reject(new Error('上传返回 URL 为空'))
								}
							} else {
								reject(new Error(res.msg || '上传失败'))
							}
						},
						(err) => {
							reject(new Error(err.msg || '上传出错'))
						}
					)
				})
			},

			checkIdentityStatus() {
				getUserIdentityStatus().then(res => {
					if (res.status === 200 && res.data) {
						const {
							identity,
							audit_identity,
							intermediary_audit
						} = res.data

						// 设置审核身份类型
						this.auditIdentity = audit_identity ? parseInt(audit_identity) : 0;

						//已有身份，跳首页
						if (identity !== 0 && identity !== '0' && identity !== null) {
							uni.redirectTo({
								url: '/pages/base/index/index'
							});
						}

						// 获取用户信息用于回显手机号
						this.getUserInfo();

						// 处理不同状态
						if (this.auditIdentity === 0) {
							// 未提交过，保持表单初始状态（可编辑）
							this.intermediaryAuditStatus = null;
						} else if (this.auditIdentity === 3) {
							// 居间人审核中，需要处理 intermediary_audit
							if (intermediary_audit) {
								// 回显数据
								this.formData.name = intermediary_audit.name || '';
								this.formData.gender = intermediary_audit.sex === 1 ? '男' : intermediary_audit
									.sex === 2 ? '女' : '';
								this.formData.years = intermediary_audit.experience || '';
								this.formData.phone = intermediary_audit.phone || '';
								this.formData.idFront = intermediary_audit.id_card_front?.trim() || '';
								this.formData.idBack = intermediary_audit.id_card_back?.trim() || '';
								this.formData.resume = intermediary_audit.certification?.trim() || '';

								// 设置具体的审核状态
								this.intermediaryAuditStatus = intermediary_audit.status ? parseInt(
									intermediary_audit.status) : 0;

								// 根据具体审核状态执行操作
								if (this.intermediaryAuditStatus === 2 && !this.hasShownRejectModal) {
									this.hasShownRejectModal = true; // 标记已弹过
									// 审核被拒绝，弹出提示框
									uni.showModal({
										title: '居间人信息审核不通过',
										content: '请修改后重新提交申请。',
										showCancel: false,
										confirmText: '我知道了'
									});
								}
								// 如果是0（审核中），则什么都不做，表单会自动禁用
							} else {
								// audit_identity=3 但 intermediary_audit 不存在，视为异常，按未提交处理
								this.auditIdentity = 0;
								this.intermediaryAuditStatus = null;
							}
						}
						// 其他 audit_identity 值理论上不会出现
					}
				}).catch(err => {
					console.error('获取身份状态失败', err);
					// 出错时，默认为未提交状态
					this.auditIdentity = 0;
					this.intermediaryAuditStatus = null;
				});
			},



			getUserInfo() {
				getBaseUserInfo().then(res => {
					if (res.status === 200 && res.data) {
						this.userInfo = {
							...res.data
						};
						// 如果表单中没有手机号，则用用户信息填充
						if (!this.formData.phone) {
							this.formData.phone = res.data.phone;
						}
					}
				}).catch(err => {
					console.log('获取用户信息失败', err);
				});
			},
			// 判断是否为本地临时文件路径（非 HTTP/HTTPS）
			isLocalPath(path) {
				return path && !/^https?:\/\//.test(path);
			},
			async submitForm() {
				if (this.isFormDisabled) return;

				const {
					name,
					gender,
					years,
					phone,
					idFront,
					idBack,
					resume
				} = this.formData;

				if (!name || !gender || !years || !phone || !idFront || !idBack || !resume) {
					uni.showToast({
						title: '请填写完整所有信息',
						icon: 'none'
					});
					return;
				}

				const sex = this.parseSex(gender);
				if (sex !== 1 && sex !== 2) {
					uni.showToast({
						title: '性别请输入“男”或“女”',
						icon: 'none'
					});
					return;
				}

				try {
					uni.showLoading({
						title: '提交中...'
					});

					// 判断是否需要上传，避免重复上传已有 URL
					const uploadIfNeeded = async (path) => {
						if (this.isLocalPath(path)) {
							return await this.uploadImage(path);
						}
						return path; // 已是线上 URL，直接返回
					};

					const [idCardFrontUrl, idCardBackUrl, certUrl] = await Promise.all([
						uploadIfNeeded(idFront),
						uploadIfNeeded(idBack),
						uploadIfNeeded(resume)
					]);

					const submitData = {
						name,
						sex,
						experience: years,
						phone,
						id_card_front: idCardFrontUrl,
						id_card_back: idCardBackUrl,
						certification: certUrl,
					};

					console.log('准备提交的数据:', submitData);

					const res = await betweenAuditSubmit(submitData);
					uni.hideLoading();

					if (res.status === 200) {
						uni.showToast({
							title: '提交成功',
							icon: 'success'
						});
						setTimeout(() => {
							const pages = getCurrentPages();
							const currentPage = pages[pages.length - 1];
							const options = currentPage.options || {};
							let url = '/pages/sub_base/between-apply/index';
							const params = [];
							for (const key in options) {
								if (options.hasOwnProperty(key)) {
									params.push(`${key}=${encodeURIComponent(options[key])}`);
								}
							}
							if (params.length > 0) {
								url += '?' + params.join('&');
							}
							uni.redirectTo({
								url
							});
						}, 1000);
					} else {
						uni.showToast({
							title: res.msg || '提交失败，请稍后重试',
							icon: 'none'
						});
					}
				} catch (error) {
					uni.hideLoading();
					uni.showToast({
						title: error || '操作失败',
						icon: 'none'
					});
					console.error('提交过程出错:', error);
				}
			}
		}
	}
</script>

<style scoped>
	.container {
		min-height: 100vh;
		background-color: #ffffff;
		box-sizing: border-box;
		padding-bottom: 40rpx;
		position: relative;
	}

	.header {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 27.76rpx;
		z-index: 100;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.header-left {
		width: 76.34rpx;
		height: 76.34rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.menu-icon {
		width: 45rpx;
		height: 45rpx;
	}

	.header-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.header-right {
		width: 76.34rpx;
		height: 76.34rpx;
	}

	.form-container {
		padding: 0 30rpx;
	}

	.form-item {
		display: flex;
		align-items: center;
		margin: 30rpx 0;
		border-bottom: 1rpx solid #eee;
		padding-bottom: 20rpx;
		position: relative;
		/* 为 placeholder 定位 */
	}

	.label {
		font-size: 28rpx;
		color: #333;
		width: 180rpx;
	}

	.input {
		flex: 1;
		font-size: 28rpx;
		padding: 0;
		margin: 0;
	}

	.placeholder {
		/* position: absolute; */
		/* right: 0; */
		color: #999;
		font-size: 28rpx;
	}

	.upload-section {
		margin-top: 40rpx;
	}

	.section-title {
		font-size: 30rpx;
		color: #333;
		margin-bottom: 20rpx;
		display: block;
	}

	.id-card-container {
		display: flex;
		justify-content: space-between;
	}

	.card-item {
		width: 48%;
		position: relative;
		border-radius: 12rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.card-image {
		width: 100%;
		height: 300rpx;
		background-color: #f0f0f0;
	}

	.example-section {
		margin-top: 40rpx;
	}

	.example-title {
		font-size: 28rpx;
		color: #333;
		display: block;
		margin-bottom: 10rpx;
	}

	.example-tip {
		font-size: 24rpx;
		color: #999;
		line-height: 1.5;
	}

	.example-images {
		display: flex;
		justify-content: space-between;
		margin-top: 20rpx;
		flex-wrap: wrap;
	}

	.example-item {
		width: 24%;
		margin-bottom: 20rpx;
	}

	.example-img {
		width: 100%;
		height: 140rpx;
		border-radius: 12rpx;
		background-color: #f0f0f0;
	}

	.example-label {
		display: block;
		text-align: center;
		font-size: 24rpx;
		color: #666;
		margin-top: 8rpx;
	}

	.upload-resume-section {
		margin-top: 40rpx;
	}

	.resume-upload {
		width: 200rpx;
		height: 200rpx;
		border-radius: 12rpx;
		background-color: #f0f0f0;
		display: flex;
		align-items: center;
		justify-content: center;
		overflow: hidden;
		position: relative;
	}

	.resume-preview {
		width: 100%;
		height: 100%;
	}

	.resume-add {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.add-icon {
		font-size: 60rpx;
		color: #999;
	}

	.submit-btn {
		margin-top: 60rpx;
		width: 90%;
		height: 88rpx;
		background-color: #ff7b3d;
		color: white;
		border-radius: 44rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
		font-weight: bold;
		margin-left: 5%;
	}

	.submit-btn.disabled {
		background-color: #ccc;
	}
</style>